package com.nativetalk.service.four.book;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.book.TdNtBookCourse;
import com.nativetalk.bean.course.TsNtCourseInfoIndex;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.bean.member.course.TdNtMembCourseSize;
import com.nativetalk.bean.member.setmeal.TdNtMembSetmealInsert;
import com.nativetalk.bean.member.setmeal.TdNtMembSetmealList;
import com.nativetalk.bean.reserve.TdNtReserveInsert;
import com.nativetalk.bean.reserve.TdNtReserveTimeDetail;
import com.nativetalk.bean.setmeal.TsNtSetmealDetail;
import com.nativetalk.bean.teacher.TdNtTeacherTuisong;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.getui.AndroidReserveTeacher;
import com.nativetalk.common.getui.IosReserveTeacher;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.common.util.SendMailUtil;
import com.nativetalk.dao.*;
import com.pingplusplus.Pingpp;
import com.pingplusplus.model.Charge;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 2016/11/1.
 * Modified by wangzheng on 2017/1/10
 */
@Service
public class FourBookServiceImpl implements FourBookService {
    private static Logger logger = Logger.getLogger(FourBookServiceImpl.class);
    @Resource
    private TdNtMembSetmealDao tdNtMembSetmealDao;
    @Resource
    private TsNtSetmealDao tsNtSetmealDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtMembCourseSizeDao tdNtMembCourseSizeDao;
    @Resource
    private TdNtReserveDao tdNtReserveDao;
    @Resource
    private TdNtReserveTimeDao tdNtReserveTimeDao;

    @Override
    public RetInfo transferBuy(TdNtMember tdNtMember, String set_id, String userBlanace, String ip, String channel) {
        String logInfo = this.getClass().getName() + ":transferBuy:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        Map<String,Object> result = new HashMap<>();

        TsNtSetmealDetail tsNtSetmealDetail = tsNtSetmealDao.findTsNtSetmealDetail(Integer.valueOf(set_id));
        if(tsNtSetmealDetail != null){
            Map<String,Integer> map = new HashMap<>();
            map.put("memb_id",tdNtMember.getMemb_id());
            map.put("set_id",Integer.valueOf(set_id));
            TdNtMembSetmealList tdNtMembSetmealList = tdNtMembSetmealDao.findTdNtMembSetmealBymembId(map);
            if (tdNtMembSetmealList == null) {
                BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtMember.getMemb_id());

                Pingpp.apiKey = Constants.Live_Secret_Key;
                Map<String, Object> chargeParams = new HashMap<String, Object>();
                chargeParams.put("order_no", CommonUtil.getOrderNub());
                //判断是否使用余额：0表示使用，1表示不使用
                if(userBlanace.equals("0")) {
                    chargeParams.put("amount", tsNtSetmealDetail.getSet_amout().subtract(memb_balance).multiply(new BigDecimal(100)).intValue());  //单位为分
                }
                else {
                    chargeParams.put("amount", tsNtSetmealDetail.getSet_amout().multiply(new BigDecimal(100)).intValue()); //单位为分
//                    chargeParams.put("amount", 1);// 测试时使用
                }

                Map<String, String> app = new HashMap<String, String>();
                app.put("id", Constants.APP_ID);
                chargeParams.put("app", app);
                chargeParams.put("channel", channel);  //微信wx
                chargeParams.put("currency", "cny");
                chargeParams.put("client_ip", ip);
                chargeParams.put("subject", "外教君购买课程");
                chargeParams.put("body", "外教君购买课程");
                try {
                    Charge charge = Charge.create(chargeParams);
                    result.put("charge", charge);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("跳转成功");
                    retInfo.setObj(result);
                } catch (Exception e) {
                    retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
                    retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
                    logger.error(e.getMessage(),e);
                }

            }
            else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("MEMB.SETMEAL.NOTNULL"));
            }
        }
        else {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip(ValidationMessages.getValue("SETMEAL.RESULT.NULL"));
        }

        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo transferListenBuy(TdNtMember tdNtMember, String userBlanace, BigDecimal listen_price, String ip, String channel) {
        String logInfo = this.getClass().getName() + ":transferListenBuy:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        Map<String,Object> result = new HashMap<>();

        BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtMember.getMemb_id());

        Pingpp.apiKey = Constants.Live_Secret_Key;
        Map<String, Object> chargeParams = new HashMap<String, Object>();
        chargeParams.put("order_no", CommonUtil.getOrderNub());
        //判断是否使用余额：0表示使用，1表示不使用
        if(userBlanace.equals("0")) {
            chargeParams.put("amount", listen_price.subtract(memb_balance).multiply(new BigDecimal(100)).intValue()); //金额单位为分
        }
        else {
            chargeParams.put("amount", listen_price.multiply(new BigDecimal(100)).intValue()); //金额单位为分
        }
        Map<String, String> app = new HashMap<String, String>();
        app.put("id", Constants.APP_ID);
        chargeParams.put("app", app);
        chargeParams.put("channel", channel);  //微信wx
        chargeParams.put("currency", "cny");
        chargeParams.put("client_ip", ip);
        chargeParams.put("subject", "外教君购买试听课");
        chargeParams.put("body", "外教君购买试听课");
        try {
            Charge charge = Charge.create(chargeParams);
            result.put("charge", charge);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("跳转成功");
            retInfo.setObj(result);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }

        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo addBook(TdNtBookCourse tdNtBookCourse, TdNtMember tdNtMember, String ip) {
        String logInfo = this.getClass().getName() + ":addBook:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            Map<String,Object> result = new HashMap<>();
            TsNtSetmealDetail tsNtSetmealDetail = tsNtSetmealDao.findTsNtSetmealDetail(Integer.valueOf(tdNtBookCourse.getSet_id()));
            //套餐存在
            if (tsNtSetmealDetail != null) {
                TdNtMembSetmealInsert tdNtMembSetmealInsert = new TdNtMembSetmealInsert();
                //根据setmeal里的cou_id(即course表里的cate_id)找出对应course表里的cou_id
                Map<String , List<TsNtCourseInfoIndex>> courseMap = (Map<String , List<TsNtCourseInfoIndex>>)MemcachedUtils.get(MemcachedKey.tsNtCourseInfoIndexMap);
                List<TsNtCourseInfoIndex> tsNtCourseInfoIndexs = courseMap.get(tsNtSetmealDetail.getCou_id()+"");
                tdNtMembSetmealInsert.setCou_id(tsNtCourseInfoIndexs.get(0).getCou_id());
                tdNtMembSetmealInsert.setEnd_time(new Timestamp(CommonUtil.getTime(tsNtSetmealDetail.getSet_type(),tsNtSetmealDetail.getSize())));
                tdNtMembSetmealInsert.setMemb_id(tdNtMember.getMemb_id());
                tdNtMembSetmealInsert.setMinute_amout(tsNtSetmealDetail.getSet_amout().divide(
                        new BigDecimal(tsNtSetmealDetail.getSet_time()),2, BigDecimal.ROUND_HALF_EVEN));
                tdNtMembSetmealInsert.setOriginal_price(tsNtSetmealDetail.getOriginal_price());
                tdNtMembSetmealInsert.setSet_amout(tsNtSetmealDetail.getSet_amout());
                tdNtMembSetmealInsert.setSet_id(tsNtSetmealDetail.getSet_id());
                tdNtMembSetmealInsert.setSet_limit(tsNtSetmealDetail.getSet_limit());
                tdNtMembSetmealInsert.setSet_name(tsNtSetmealDetail.getSet_name());
                tdNtMembSetmealInsert.setSet_synopis(tsNtSetmealDetail.getSet_synopis());
                tdNtMembSetmealInsert.setSet_time(tsNtSetmealDetail.getSet_time());
                tdNtMembSetmealInsert.setSet_type(tsNtSetmealDetail.getSet_type());
                tdNtMembSetmealInsert.setSurplus_time(tsNtSetmealDetail.getSet_time());
                tdNtMembSetmealInsert.setSet_picture(tsNtSetmealDetail.getSet_picture());
                tdNtMembSetmealInsert.setSize(tsNtSetmealDetail.getSize());
                tdNtMembSetmealInsert.setSet_reserve_size(tsNtSetmealDetail.getCou_size());
                TdNtMembFoundChangeInset tdNtMembFoundChangeInset;
                TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();

                BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtMember.getMemb_id());

                int money_change_type;
                String change_name;
                if ("alipay".equals(tdNtBookCourse.getChannel())) {
                    //类型为支付宝支付
                    money_change_type = Constants.PaymentChannel.alipay;
                    change_name = "支付宝购买课程";
                } else if ("wx".equals(tdNtBookCourse.getChannel())) {
                    //类型为微信支付
                    money_change_type = Constants.PaymentChannel.wxpay;
                    change_name = "微信购买课程";
                }
                else {
                    money_change_type = Constants.PaymentChannel.wallet;
                    change_name = "购买课程";
                }

                String orderNo = tdNtBookCourse.getOrderNo();

                //判断是否使用余额 0表示使用
                if (tdNtBookCourse.getUserBlanace().equals("0")) {
                    //判断余额是否足够
                    if (memb_balance.compareTo(tsNtSetmealDetail.getSet_amout()) > -1) {

                        memb_balance = memb_balance.subtract(tsNtSetmealDetail.getSet_amout());
                        tdNtMemberInvite.setMemb_balance(memb_balance);
                        tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());

                        tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                        /**
                         * 添加资金变动记录
                         */
                        tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                        tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance.add(tsNtSetmealDetail.getSet_amout()));
                        tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance);
                        tdNtMembFoundChangeInset.setMfchg_change_amount(tsNtSetmealDetail.getSet_amout());
                        tdNtMembFoundChangeInset.setMfchg_change_name("购买课程");
                        tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                        tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                        tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                        tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());
                        tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);

                        tdNtMembSetmealInsert.setState(Constants.SetMealPayState.paid);
                        tdNtMembSetmealInsert.setMfchg_id(tdNtMembFoundChangeInset.getMfchg_id());
                        /**
                         * 更新余额
                         */
                        tdNtMember.setMemb_balance(memb_balance);
                        tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);
                    }
                    //余额不足
                    else {
                        /**
                         * 检验订单号
                         */
                        if(null == orderNo || "".equals(orderNo.trim())){
                            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                            retInfo.setTip("传入的订单号为null或空");
                            return retInfo;
                        }

                        tdNtMemberInvite.setMemb_balance(new BigDecimal(0));
                        tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());

                        tdNtMembFoundChangeInset = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
                        /**
                         * notify异步先返回，该订单的记录已插入数据库
                         */
                        if(null != tdNtMembFoundChangeInset){
                            //补全第三方支付的订单信息
                            tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                            tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                            tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                            tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                            tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                            tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                            tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChangeInset);
                        }
                        else{
                            tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                            //支付宝或微信支付要添加的记录
                            tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                            tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                            tdNtMembFoundChangeInset.setMfchg_change_amount(tsNtSetmealDetail.getSet_amout().subtract(memb_balance));
                            tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                            tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                            tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                            tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                            tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                            tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                            tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                        }

                        //账户余额支付要添加的记录
                        tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                        tdNtMembFoundChangeInset.setMfchg_change_amount(memb_balance);
                        tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance);
                        tdNtMembFoundChangeInset.setMfchg_back_amount(new BigDecimal(0));
                        tdNtMembFoundChangeInset.setMfchg_change_name("购买课程");
                        tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                        tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                        tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                        tdNtMembFoundChangeInset.setMoney_change_type(Constants.PaymentChannel.wallet);
                        tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                        tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);

                        tdNtMembSetmealInsert.setState(Constants.SetMealPayState.paid);
                        tdNtMembSetmealInsert.setMfchg_id(tdNtMembFoundChangeInset.getMfchg_id());
                        /**
                         * 更新余额
                         */
                        tdNtMember.setMemb_balance(new BigDecimal(0));
                        tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);

                    }

                }
                //使用第三方支付
                else {
                    /**
                     * 检验订单号
                     */
                    if(null == orderNo || "".equals(orderNo.trim())){
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip("传入的订单号为null或空");
                        return retInfo;
                    }

                    tdNtMembFoundChangeInset = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
                    /**
                     * notify异步先返回，该订单的记录已插入数据库
                     */
                    if(null != tdNtMembFoundChangeInset){
                        //补全第三方支付的订单信息
                        tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                        tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                        tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                        tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                        tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                        tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChangeInset);
                    }
                    else{
                        tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                        //支付宝或微信支付要添加的记录
                        tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                        tdNtMembFoundChangeInset.setMfchg_change_amount(tsNtSetmealDetail.getSet_amout());
                        tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                        tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                        tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                        tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                        tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                        tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                        tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                    }

                    tdNtMembSetmealInsert.setState(Constants.SetMealPayState.paid);
                    tdNtMembSetmealInsert.setMfchg_id(tdNtMembFoundChangeInset.getMfchg_id());

                }

                tdNtMembSetmealDao.inserttdNtMembSetmeal(tdNtMembSetmealInsert);

                /**
                 * 更新套餐购买人数
                 */
                Map<String, Object> updateSetMeal = new HashMap<>();
                tsNtSetmealDetail.setSet_size(tsNtSetmealDetail.getSet_size()+1);
                updateSetMeal.put("set_id",tsNtSetmealDetail.getSet_id());
                updateSetMeal.put("set_size",tsNtSetmealDetail.getSet_size());
                tsNtSetmealDao.updateTsNtSetmealSize(updateSetMeal);

                /**
                 * 更新用户购买的课程的剩余总次数
                 */
                Map<String,Object> map1 = new HashMap<>();
                map1.put("memb_id",tdNtMember.getMemb_id());
                map1.put("cou_id",tdNtBookCourse.getCou_id());
                TdNtMembCourseSize tdNtMembCourseSize = tdNtMembCourseSizeDao.findTdNtMembCourseSizeByMembIdAndCouId(map1);
                if(null == tdNtMembCourseSize){
                    tdNtMembCourseSizeDao.insertTdNtMembCourseSize(new TdNtMembCourseSize(tdNtMember.getMemb_id(), tdNtBookCourse.getCou_id(), tsNtSetmealDetail.getCou_size()));
                }
                else{
                    tdNtMembCourseSizeDao.updateTdNtMembCourseSizeByMembIdAndCouId(
                            new TdNtMembCourseSize(tdNtMember.getMemb_id(), tdNtBookCourse.getCou_id(), (tdNtMembCourseSize.getCou_size() + tsNtSetmealDetail.getCou_size())));
                }
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("够买课程成功");
                retInfo.setObj(result);
            }
            else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("MEMB.SETMEAL.NOTNULL"));
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo addListenBook(TdNtBookCourse tdNtBookCourse, TdNtMember tdNtMember, String userBlanace, String ip, String channel, String orderNo) {
        String logInfo = this.getClass().getName() + ":addBook:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            Map<String,Object> result = new HashMap<>();
            TdNtMembFoundChangeInset tdNtMembFoundChangeInset;
            TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();

            int money_change_type;
            String change_name;
            if("alipay".equals(channel)){
                //类型为支付宝支付
                money_change_type = Constants.PaymentChannel.alipay;
                change_name = "支付宝购买课程";
            }
            else if("wx".equals(channel)){
                //类型为微信支付
                money_change_type = Constants.PaymentChannel.wxpay;
                change_name = "微信购买课程";
            }
            else {
                money_change_type = Constants.PaymentChannel.wallet;
                change_name = "购买课程";
            }

            BigDecimal memb_balance = tdNtMemberDao.findTdNtMemberBalabce(tdNtMember.getMemb_id());

            //判断是否使用余额 0表示使用
            if (userBlanace.equals("0")) {
                //判断余额是否足够
                if (memb_balance.compareTo(tdNtBookCourse.getListen_price()) > -1) {

                    memb_balance = memb_balance.subtract(tdNtBookCourse.getListen_price());
                    tdNtMemberInvite.setMemb_balance(memb_balance);
                    tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());
                    /**
                     * 添加资金变动记录
                     */
                    tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                    tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                    tdNtMembFoundChangeInset.setMfchg_back_amount(memb_balance);
                    tdNtMembFoundChangeInset.setMfchg_change_amount(tdNtBookCourse.getListen_price());
                    tdNtMembFoundChangeInset.setMfchg_change_name("购买课程");
                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                    tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance.add(tdNtBookCourse.getListen_price()));
                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                    tdNtMembFoundChangeInset.setMfchg_number(CommonUtil.getOrderNub());
                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                    /**
                     * 更新余额
                     */
                    tdNtMember.setMemb_balance(memb_balance);
                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);

                }
                //余额不充足
                else {
                    /**
                     * 检验订单号
                     */
                    if(null == orderNo || "".equals(orderNo.trim())){
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip("传入的订单号为null或空");
                        return retInfo;
                    }

                    tdNtMemberInvite.setMemb_balance(new BigDecimal(0));
                    tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());

                    tdNtMembFoundChangeInset = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
                    /**
                     * notify异步先返回，该订单的记录已插入数据库
                     */
                    if(null != tdNtMembFoundChangeInset){
                        //补全第三方支付的订单信息
                        tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                        tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                        tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                        tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                        tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                        tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChangeInset);
                    }
                    else{
                        tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                        //支付宝或微信支付要添加的记录
                        tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                        tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                        tdNtMembFoundChangeInset.setMfchg_change_amount(tdNtBookCourse.getListen_price().subtract(memb_balance));
                        tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                        tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                        tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                        tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                        tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                        tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                        tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                    }
                    //账户余额支付要添加的记录
                    tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                    tdNtMembFoundChangeInset.setMfchg_back_amount(new BigDecimal(0));
                    tdNtMembFoundChangeInset.setMfchg_change_amount(memb_balance);
                    tdNtMembFoundChangeInset.setMfchg_change_name("购买课程");
                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                    tdNtMembFoundChangeInset.setMfchg_front_amount(memb_balance);
                    tdNtMembFoundChangeInset.setMoney_change_type(Constants.PaymentChannel.wallet);
                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                    tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                    /**
                     * 更新余额
                     */
                    tdNtMember.setMemb_balance(new BigDecimal(0));
                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);

                }

            }
            //使用第三方支付
            else {
                /**
                 * 检验订单号
                 */
                if(null == orderNo || "".equals(orderNo.trim())){
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("传入的订单号为null或空");
                    return retInfo;
                }

                tdNtMembFoundChangeInset = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
                /**
                 * notify异步先返回，该订单的记录已插入数据库
                 */
                if(null != tdNtMembFoundChangeInset){
                    //补全第三方支付的订单信息
                    tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                    tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                    tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                    tdNtMembFoundChangeDao.updatePaymentInfo(tdNtMembFoundChangeInset);
                }
                else{
                    tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();

                    //支付宝或微信支付要添加的记录
                    tdNtMembFoundChangeInset.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMembFoundChangeInset.setMfchg_change_month(CommonUtil.getMonth(now));
                    tdNtMembFoundChangeInset.setMfchg_change_amount(tdNtBookCourse.getListen_price());
                    tdNtMembFoundChangeInset.setMfchg_change_type(Constants.FundChangeType.wallet_out);
                    tdNtMembFoundChangeInset.setState(Constants.PayState.success);
                    tdNtMembFoundChangeInset.setType(Constants.ChargeType.buy_course_code);
                    tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                    tdNtMembFoundChangeInset.setMoney_change_type(money_change_type);
                    tdNtMembFoundChangeInset.setMfchg_change_name(change_name);
                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);
                }
            }

            /**
             * 添加试听课的预约记录
             */
            TdNtReserveInsert tdNtReserveInsert = new TdNtReserveInsert();
            tdNtReserveInsert.setReserve_time(30);
            tdNtReserveInsert.setTea_id(tdNtBookCourse.getTea_id());
            tdNtReserveInsert.setReserve_start_time(tdNtBookCourse.getReserve_start_time());
            tdNtReserveInsert.setReserve_end_time(tdNtBookCourse.getReserve_end_time());
            tdNtReserveInsert.setCou_id(tdNtBookCourse.getCou_id());
            tdNtReserveInsert.setMemb_id(tdNtMember.getMemb_id());
            tdNtReserveInsert.setAmout(tdNtBookCourse.getListen_price());
            tdNtReserveInsert.setState(Constants.ReserveState.ready_to_begin);//待上课
            tdNtReserveInsert.setType(Constants.ReserveType.listen_course);//试听课
            tdNtReserveDao.insertTdNtReserve(tdNtReserveInsert);

            /**
             * 更新老师端开通的时间状态变为已预约
             */
            Date date1 = new Date(tdNtReserveInsert.getReserve_start_time().getTime());
            TdNtReserveTimeDetail tdNtReserveTimeDetail = new TdNtReserveTimeDetail();
            tdNtReserveTimeDetail.setReserve_time(CommonUtil.getHour(date1));
            tdNtReserveTimeDetail.setTea_id(tdNtReserveInsert.getTea_id());
            tdNtReserveTimeDetail.setDate(date1);
            tdNtReserveTimeDetail.setIs_valid(Constants.ReserveTimeState.booked);
            tdNtReserveTimeDao.updateTdNtReserveTimeSetIsValid(tdNtReserveTimeDetail);

            /**
             *  给教师发推送及邮件
             */
            TdNtTeacherTuisong tdNtTeacherTuisong = tdNtTeacherDao.findTdNtTeacherTuisong(tdNtReserveInsert.getTea_id());
            if (tdNtTeacherTuisong.getEqu_client_id() != null && !(tdNtTeacherTuisong.getEqu_client_id().equals("1212313fasdf"))) {
                /**
                 * 发推送
                 */
                if (tdNtTeacherTuisong.getEqu_type().equals("1")) {
                    AndroidReserveTeacher.apnpush("NativeTalk", "Dear NativeTalk tutor, new assignment class, please check the time for the class.\n ",
                            tdNtTeacherTuisong.getEqu_client_id(), tdNtReserveInsert.getReserve_id());
                } else {
                    logger.info(tdNtTeacherTuisong.getEqu_client_id());
                    IosReserveTeacher.apnpush("NativeTalk", "Dear NativeTalk tutor, new assignment class, please check the time for the class.\n ",
                            tdNtTeacherTuisong.getEqu_client_id(), tdNtReserveInsert.getReserve_id());

                }
                /**
                 * 发邮件
                 */
                SendMailUtil.sendMail(tdNtTeacherTuisong.getTea_email(), "[NativeTalk]", "Dear NativeTalk tutor, <br><br>" +
                        "There is an appointment class, please check your class time in \"Appointments\" on your homepage. " +
                        "And please call the student on time. Thank you!<br><br>" +
                        "Best Regards,<br><br>" + "NativeTalk Team");

            }

            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("够买试听课成功");
            retInfo.setObj(result);

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
